<template>
    <view class="order-page">
      <!-- 全局发布弹框 -->
      <PublishModal ref="publishModalRef" />

      <!-- 顶部背景 -->
      <image class="order-header-bg" src="/static/header-bg.png" mode="aspectFill" />

      <!-- 固定顶部区域 -->
      <view class="fixed-header">
        <!-- 主标签切换 -->
        <view class="spacer"></view>

        <view class="main-tabs">
          <text 
            :class="['main-tab-item', { 'active': activeMainTab === 'published' }]" 
            @click="switchMainTab('published')"
          >
            我发布的
          </text>
          <text 
            :class="['main-tab-item', { 'active': activeMainTab === 'participated' }]" 
            @click="switchMainTab('participated')"
          >
            我参与的
          </text>
        </view>

        <!-- 状态筛选标签 -->
        <scroll-view class="status-tabs" scroll-x :show-scrollbar="false">
          <view class="status-tabs-container">
            <text 
              v-for="status in statusList" 
              :key="status.value"
              :class="['status-tab-item', { 'active': activeStatus === status.value }]" 
              @click="switchStatus(status.value)"
            >
              {{ status.label }}
            </text>
          </view>
        </scroll-view>
      </view>

      <!-- 订单列表 -->
      <scroll-view scroll-y class="order-list">
        <view 
          v-for="(order, index) in filteredOrders" 
          :key="order.id" 
          class="order-card"
          @click="handleOrderClick(order)"
        >
          <!-- 订单标题和标签 -->
          <view class="order-header">
            <view class="title-wrapper">
              <text class="order-title">{{ order.title }}</text>
              <view class="buddy-type-badge">{{ order.tag }}</view>
            </view>
            <view class="order-tags">
              <view
                :class="['status-tag', `status-${order.status}`]"
                :style="getStatusStyle(order.status)"
              >
                {{ getStatusText(order.status) }}
              </view>
            </view>
          </view>

          <!-- 发布时间 -->
          <text class="publish-time">发布于{{ order.publishTime }}</text>

          <!-- 活动时间 -->
          <view class="event-time">
        <image src="/static/time.png" class="event-icon" mode="aspectFit"></image>
            <text>{{ order.eventTime }}</text>
          </view>

          <!-- 活动地点 -->
          <view class="event-location">
        <image src="/static/location-small.png" class="event-icon" mode="aspectFit"></image>
            <text>{{ order.location }}</text>
          </view>

          <!-- 活动详情标签 -->
          <view class="detail-tags">
            <view class="detail-tag">{{ order.genderRestriction }}</view>
            <view class="detail-tag">{{ order.participantCount }}人</view>
            <view class="detail-tag">距离{{ order.distance }}</view>
          </view>

          <!-- 参与者、价格、操作按钮 -->
          <view class="order-footer">
            <view class="participants">
              <view class="participant-avatars" v-if="order.participants && order.participants.length">
                <image 
                  v-for="(avatar, idx) in order.participants" 
                  :key="idx" 
                  :src="avatar" 
                  class="participant-avatar"
                  mode="aspectFill"
                ></image>
                <view class="participant-more" v-if="order.hasMoreParticipants">…</view>
              </view>
              <text class="participant-count" v-if="order.participantsCount > 0">已有{{ order.participantsCount }}人参与</text>
              <text class="participant-count" v-else>暂无人参与</text>
            </view>
            <view class="action-section">
              <text class="price">¥{{ order.price }}</text>
              <!-- 我参与的订单，进行中状态显示两个按钮 -->
              <view v-if="shouldShowParticipatedActions(order)" class="participated-actions">
                <button 
                  class="action-button cancel-btn"
                  @click.stop="handleParticipatedCancel(order)"
                >
                  取消
                </button>
                <button 
                  class="action-button confirm-btn"
                  @click.stop="handleParticipatedConfirm(order)"
                >
                  确认订单
                </button>
              </view>
              <!-- 其他状态显示单个按钮 -->
              <button 
                v-else-if="shouldShowActionButton(order)"
                :class="['action-button', `action-${order.status}`]"
                @click.stop="handleAction(order)"
              >
                {{ getActionText(order.status) }}
              </button>
            </view>
          </view>

          <!-- 背景装饰 -->
          <view class="card-bg">
            <image src="/static/game.png" class="bg-image" mode="aspectFit"></image>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 自定义底部导航 -->
    <CustomTabBar />
  </template>
  
<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import PublishModal from '@/pages/components/PublishModal.vue'
import CustomTabBar from '@/pages/components/CustomTabBar.vue'
import BuddyApi from '@/sheep/api/member/buddy'

const activeMainTab = ref('published')
const activeStatus = ref('all')

// 我发布的订单状态列表
const publishedStatusList = ref([
  { label: '全部', value: 'all' },
  { label: '接单中', value: 'taking' },
  { label: '进行中', value: 'in_progress' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' }
])

// 我参与的订单状态列表
const participatedStatusList = ref([
  { label: '全部', value: 'all' },
  { label: '待开始', value: 'pending_start' },
  { label: '进行中', value: 'in_progress' },
  { label: '已被拒绝', value: 'rejected' },
  { label: '已取消', value: 'cancelled' },
  { label: '待发布人确认', value: 'pending_confirm' },
  { label: '已完成', value: 'completed' },
  { label: '已评价', value: 'pending_review' }
])

// 根据当前标签页返回对应的状态列表
const statusList = computed(() => {
  return activeMainTab.value === 'published' ? publishedStatusList.value : participatedStatusList.value
})

const publishedOrders = ref([])
const participatedOrders = ref([])
const listLoading = ref(false)
const hasLoadedPublished = ref(false)
const hasLoadedParticipated = ref(false)

const publishModalRef = ref(null)

const formatDateTime = (time) => {
  if (!time) return '--'
  try {
    const date = new Date(time)
    if (Number.isNaN(date.getTime())) {
      return typeof time === 'string' ? time : '--'
    }
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`
  } catch (err) {
    console.error('formatDateTime error:', err)
    return typeof time === 'string' ? time : '--'
  }
}

const formatEventTime = (time) => {
  if (!time) return '待定'
  try {
    const date = new Date(time)
    if (Number.isNaN(date.getTime())) {
      return typeof time === 'string' ? time : '待定'
    }
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${month}月${day}日 ${hours}:${minutes}`
  } catch (err) {
    console.error('formatEventTime error:', err)
    return typeof time === 'string' ? time : '待定'
  }
}

const formatGenderLimit = (genderLimit) => {
  if (genderLimit === 1 || genderLimit === '1') return '仅限男生'
  if (genderLimit === 2 || genderLimit === '2') return '仅限女生'
  return '男女不限'
}

const formatDistance = (distance) => {
  if (distance === null || distance === undefined || distance === '') return '--'
  const value = Number(distance)
  if (Number.isNaN(value)) {
    return typeof distance === 'string' ? distance : '--'
  }
  if (value < 1000) {
    return `${Math.round(value)}m`
  }
  return `${(value / 1000).toFixed(1)}km`
}

// 我发布的订单状态映射：0-接单中，1-进行中，2-已完成，3-已取消
const normalizePublishedStatus = (status) => {
  if (status === null || status === undefined) return 'taking'
  const numeric = Number(status)
  if (!Number.isNaN(numeric)) {
    if (numeric === 0) return 'taking'      // 接单中
    if (numeric === 1) return 'in_progress' // 进行中
    if (numeric === 2) return 'completed'   // 已完成
    if (numeric === 3) return 'cancelled'   // 已取消
  }
  const value = String(status).toLowerCase()
  if (['taking', 'pending', 'waiting', 'accepting', 'open'].includes(value)) return 'taking'
  if (['in_progress', 'processing', 'ongoing', 'running', 'doing'].includes(value)) return 'in_progress'
  if (['completed', 'finished', 'done', 'success', 'succeed'].includes(value)) return 'completed'
  if (['cancelled', 'canceled', 'closed', 'void'].includes(value)) return 'cancelled'
  return 'taking'
}

// 我参与的订单状态映射：0-待开始，1-进行中，2-已被拒绝，3-已取消，4-待发布人确认，5-已完成，6-待评价
const normalizeParticipatedStatus = (status) => {
  if (status === null || status === undefined) return 'pending_start'
  const numeric = Number(status)
  if (!Number.isNaN(numeric)) {
    if (numeric === 0) return 'pending_start'     // 待开始
    if (numeric === 1) return 'in_progress'       // 进行中
    if (numeric === 2) return 'rejected'          // 已被拒绝
    if (numeric === 3) return 'cancelled'         // 已取消
    if (numeric === 4) return 'pending_confirm'   // 待发布人确认
    if (numeric === 5) return 'completed'         // 已完成
    if (numeric === 6) return 'pending_review'    // 待评价
  }
  const value = String(status).toLowerCase()
  if (['pending_start', 'waiting_start', 'not_started'].includes(value)) return 'pending_start'
  if (['in_progress', 'processing', 'ongoing', 'running', 'doing'].includes(value)) return 'in_progress'
  if (['rejected', 'reject', 'refused', 'denied'].includes(value)) return 'rejected'
  if (['cancelled', 'canceled', 'closed', 'void'].includes(value)) return 'cancelled'
  if (['pending_confirm', 'waiting_confirm', 'pending_confirmation'].includes(value)) return 'pending_confirm'
  if (['completed', 'finished', 'done', 'success', 'succeed'].includes(value)) return 'completed'
  if (['pending_review', 'waiting_review', 'pending_comment', 'waiting_comment'].includes(value)) return 'pending_review'
  return 'pending_start'
}

const transformOrder = (item = {}, isPublished = true) => {
  const acceptUsers = Array.isArray(item.acceptUsers) ? item.acceptUsers : []
  const participantAvatars = acceptUsers
    .map(user => (user && user.avatar) ? user.avatar : '/static/avatars/default_avatar.png')
    .filter(Boolean)
  const participants = participantAvatars.slice(0, 5)

  // 根据订单类型使用不同的状态映射
  // 我参与的订单使用 status 字段（接单状态）
  const status = isPublished 
    ? normalizePublishedStatus(item.status)
    : normalizeParticipatedStatus(item.status)

  return {
    id: item.id,
    title: item.title || '',
    tag: item.buddyTypeName || item.buddyType || '搭子',
    status: status,
    publishTime: formatDateTime(item.publishTime || item.createTime || item.updateTime),
    eventTime: formatEventTime(item.startTime || item.appointmentTime),
    location: item.location || item.address || '',
    genderRestriction: formatGenderLimit(item.genderLimit),
    participantCount: item.participantCount ?? item.maxParticipants ?? acceptUsers.length,
    participantsCount: acceptUsers.length,
    distance: formatDistance(item.distance),
    participants,
    hasMoreParticipants: participantAvatars.length > 5,
    price: item.unitPrice || item.price || 0,
    raw: item
  }
}

const extractOrderList = (response) => {
  if (!response) return []
  if (Array.isArray(response.data)) return response.data
  if (response.data && Array.isArray(response.data.list)) return response.data.list
  if (Array.isArray(response.list)) return response.list
  if (response.data && Array.isArray(response.data.records)) return response.data.records
  return []
}

// 将前端状态值转换为后端状态数字（我发布的订单）
const getPublishedStatusNumber = (status) => {
  const statusMap = {
    'taking': 0,      // 接单中
    'in_progress': 1, // 进行中
    'completed': 2,   // 已完成
    'cancelled': 3    // 已取消
  }
  return statusMap[status] !== undefined ? statusMap[status] : null
}

// 将前端状态值转换为后端状态数字（我参与的订单）
const getParticipatedStatusNumber = (status) => {
  const statusMap = {
    'pending_start': 0,     // 待开始
    'in_progress': 1,       // 进行中
    'rejected': 2,          // 已被拒绝
    'cancelled': 3,         // 已取消
    'pending_confirm': 4,   // 待发布人确认
    'completed': 5,         // 已完成
    'pending_review': 6    // 待评价
  }
  return statusMap[status] !== undefined ? statusMap[status] : null
}

const fetchPublishedOrders = async () => {
  listLoading.value = true
  try {
    // 根据当前选择的状态构建请求参数
    const params = {}
    if (activeStatus.value !== 'all') {
      const statusNumber = getPublishedStatusNumber(activeStatus.value)
      if (statusNumber !== null) {
        params.status = statusNumber
      }
    }
    
    const res = await BuddyApi.getMyPublishedOrders(params)
    if (res && res.code === 0) {
      const list = extractOrderList(res)
      publishedOrders.value = list.map(item => transformOrder(item, true))
      hasLoadedPublished.value = true
    } else {
      uni.showToast({
        title: res?.msg || '获取订单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取我发布的订单失败:', error)
    uni.showToast({
      title: '获取订单失败，请稍后重试',
      icon: 'none'
    })
  } finally {
    listLoading.value = false
  }
}

const fetchParticipatedOrders = async () => {
  listLoading.value = true
  try {
    // 根据当前选择的状态构建请求参数
    const params = {}
    if (activeStatus.value !== 'all') {
      const statusNumber = getParticipatedStatusNumber(activeStatus.value)
      if (statusNumber !== null) {
        params.status = statusNumber
      }
    }
    
    const res = await BuddyApi.getMyAcceptedOrders(params)
    if (res && res.code === 0) {
      const list = extractOrderList(res)
      participatedOrders.value = list.map(item => transformOrder(item, false))
      hasLoadedParticipated.value = true
    } else {
      uni.showToast({
        title: res?.msg || '获取订单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取我参与的订单失败:', error)
    uni.showToast({
      title: '获取订单失败，请稍后重试',
      icon: 'none'
    })
  } finally {
    listLoading.value = false
  }
}

const currentOrders = computed(() => {
  return activeMainTab.value === 'published' ? publishedOrders.value : participatedOrders.value
})

// 由于现在从接口层面进行筛选，所以不需要前端再次筛选
// 但如果接口返回的数据需要前端再次筛选，可以保留这个函数
const filteredOrders = computed(() => {
  // 直接返回当前订单列表，因为筛选已经在接口层面完成
  return currentOrders.value || []
})

const switchMainTab = async (tab) => {
  if (activeMainTab.value === tab) {
    if (tab === 'published') {
      await fetchPublishedOrders()
    } else if (tab === 'participated') {
      await fetchParticipatedOrders()
    }
    return
  }
  activeMainTab.value = tab
  // 切换标签页时重置状态筛选
  activeStatus.value = 'all'
  if (tab === 'published' && !hasLoadedPublished.value) {
    await fetchPublishedOrders()
  }
  if (tab === 'participated' && !hasLoadedParticipated.value) {
    await fetchParticipatedOrders()
  }
}

const switchStatus = async (status) => {
  activeStatus.value = status
  // 切换状态时重新获取订单列表
  if (activeMainTab.value === 'published') {
    await fetchPublishedOrders()
  } else if (activeMainTab.value === 'participated') {
    await fetchParticipatedOrders()
  }
}

const getStatusText = (status) => {
  const statusMap = {
    // 我发布的订单状态
    'taking': '接单中',
    'in_progress': '进行中',
    'completed': '已完成',
    'cancelled': '已取消',
    // 我参与的订单状态
    'pending_start': '待开始',
    'in_progress': '进行中',
    'rejected': '已被拒绝',
    'cancelled': '已取消',
    'pending_confirm': '待发布人确认',
    'completed': '已完成',
    'pending_review': '已评价'
  }
  return statusMap[status] || status || '未知状态'
}

// 根据状态获取样式
const getStatusStyle = (status) => {
  const styleMap = {
    'in_progress': 'linear-gradient(90deg, #EE1C1C 0%, #FFB96F 67%, rgba(255, 185, 111, 0) 96%)',
    'taking': 'linear-gradient(90deg, #B276FF 0%, #74A7FF 41%, rgba(116, 167, 255, 0) 96%)',
    'pending_start': 'linear-gradient(90deg, #9C27B0 0%, #BA68C8 50%, rgba(156, 39, 176, 0) 96%)',
    'completed': 'linear-gradient(90deg, #4CAF50 0%, #81C784 50%, rgba(76, 175, 80, 0) 96%)',
    'cancelled': 'linear-gradient(90deg, #9E9E9E 0%, #BDBDBD 50%, rgba(158, 158, 158, 0) 96%)',
    'rejected': 'linear-gradient(90deg, #FF9800 0%, #FFB74D 50%, rgba(255, 152, 0, 0) 96%)',
    'pending_confirm': 'linear-gradient(90deg, #2196F3 0%, #64B5F6 50%, rgba(33, 150, 243, 0) 96%)',
    'pending_review': 'linear-gradient(90deg, #4CAF50 0%, #81C784 50%, rgba(76, 175, 80, 0) 96%)'
  }
  return {
    background: styleMap[status] || 'linear-gradient(90deg, #B276FF 0%, #74A7FF 41%, rgba(116, 167, 255, 0) 96%)'
  }
}

// 判断是否应该显示操作按钮
const shouldShowActionButton = (order) => {
  const isPublished = activeMainTab.value === 'published'
  
  if (isPublished) {
    // 我发布的订单：只有接单中状态才显示取消按钮
    return order.status === 'taking'
  } else {
    // 我参与的订单：其他状态显示单个按钮（不包括进行中、待开始、已取消、待发布人确认、已评价）
    return order.status !== 'in_progress' && order.status !== 'pending_start' && order.status !== 'cancelled' && order.status !== 'pending_confirm' && order.status !== 'pending_review'
  }
}

// 判断是否应该显示我参与的订单的双按钮（取消和确认订单）
const shouldShowParticipatedActions = (order) => {
  const isPublished = activeMainTab.value === 'published'
  if (isPublished) return false
  // 我参与的订单，进行中状态显示两个按钮
  return order.status === 'in_progress'
}

const getActionText = (status) => {
  const isPublished = activeMainTab.value === 'published'
  
  if (isPublished) {
    // 我发布的订单操作按钮
    const publishedActionMap = {
      'taking': '取消',
      'in_progress': '去确认',
      'completed': '已完成',
      'cancelled': '已取消'
    }
    return publishedActionMap[status] || '操作'
  } else {
    // 我参与的订单操作按钮
    const participatedActionMap = {
      'pending_start': '待开始',
      'in_progress': '进行中',
      'rejected': '已被拒绝',
      'cancelled': '已取消',
      'pending_confirm': '待确认',
      'completed': '去评价',
      'pending_review': '去评价'
    }
    return participatedActionMap[status] || '操作'
  }
}

// 处理订单卡片点击
const handleOrderClick = (order) => {
  const isPublished = activeMainTab.value === 'published'
  
  if (isPublished) {
    // 我发布的订单，都可以进入确认页面查看接单人列表
    console.log('点击订单，准备跳转:', order.id, order.status)
    uni.navigateTo({
      url: `/pages/buddy/confirm?id=${order.id}`,
      fail: (err) => {
        console.error('跳转失败:', err)
        uni.showToast({
          title: '跳转失败，请重试',
          icon: 'none'
        })
      }
    })
  }
}

const handleAction = (order) => {
  const isPublished = activeMainTab.value === 'published'
  
  if (isPublished) {
    // 我发布的订单操作
    switch (order.status) {
      case 'taking':
        uni.showModal({
          title: '确认取消',
          content: '确定要取消这个订单吗？',
          success: async (res) => {
            if (res.confirm) {
              try {
                const cancelRes = await BuddyApi.cancelBuddyOrder(order.id)
                if (cancelRes && cancelRes.code === 0) {
                  uni.showToast({
                    title: '订单已取消',
                    icon: 'success'
                  })
                  // 刷新订单列表
                  await fetchPublishedOrders()
                } else {
                  uni.showToast({
                    title: cancelRes?.msg || '取消订单失败',
                    icon: 'none'
                  })
                }
              } catch (error) {
                console.error('取消订单失败:', error)
                uni.showToast({
                  title: '取消订单失败，请稍后重试',
                  icon: 'none'
                })
              }
            }
          }
        })
        break
      case 'in_progress':
        // 跳转到确认订单页面
        sheep.$router.go('/pages/buddy/confirm', { id: order.id })
        break
      default:
        uni.showToast({
          title: '该状态无法操作',
          icon: 'none'
        })
    }
  } else {
    // 我参与的订单操作
    switch (order.status) {
      case 'pending_start':
        uni.showToast({
          title: '订单待开始',
          icon: 'none'
        })
        break
      case 'pending_confirm':
        uni.showToast({
          title: '等待发布人确认',
          icon: 'none'
        })
        break
      case 'completed':
      case 'pending_review':
        // 跳转到评价页面
        // 我参与的订单需要使用原始数据中的buddyOrderId
        const buddyOrderId = order.raw?.buddyOrderId || order.id
        uni.navigateTo({
          url: `/pages/buddy/review?buddyOrderId=${buddyOrderId}`,
          fail: (err) => {
            console.error('跳转失败:', err)
            uni.showToast({
              title: '跳转失败，请重试',
              icon: 'none'
            })
          }
        })
        break
      case 'in_progress':
        uni.showToast({
          title: '订单进行中',
          icon: 'none'
        })
        break
      default:
        uni.showToast({
          title: '该状态无法操作',
          icon: 'none'
        })
    }
  }
}

// 处理我参与的订单取消
const handleParticipatedCancel = async (order) => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消这个订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const cancelRes = await BuddyApi.cancelAcceptedOrder(order.id)
          if (cancelRes && cancelRes.code === 0) {
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            })
            // 刷新订单列表
            await fetchParticipatedOrders()
          } else {
            uni.showToast({
              title: cancelRes?.msg || '取消订单失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('取消订单失败:', error)
          uni.showToast({
            title: '取消订单失败，请稍后重试',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 处理我参与的订单确认
const handleParticipatedConfirm = async (order) => {
  uni.showModal({
    title: '确认订单',
    content: '确定要确认完成这个订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 从原始订单数据中获取 needConfirm 和 acceptId
          const rawOrder = order.raw || {}
          const needConfirm = rawOrder.needConfirm === true || rawOrder.needConfirm === 1
          const acceptId = rawOrder.acceptId || rawOrder.id
          
          let longitude, latitude
          
          // 如果需要现场确认，获取用户位置
          if (needConfirm) {
            try {
              const locationRes = await new Promise((resolve, reject) => {
                uni.getLocation({
                  type: 'gcj02',
                  success: (res) => {
                    resolve(res)
                  },
                  fail: (err) => {
                    reject(err)
                  }
                })
              })
              longitude = locationRes.longitude
              latitude = locationRes.latitude
            } catch (locationError) {
              console.error('获取位置失败:', locationError)
              uni.showToast({
                title: '获取位置失败，请检查定位权限',
                icon: 'none'
              })
              return
            }
          }
          
          const confirmRes = await BuddyApi.confirmParticipatedOrder(
            acceptId,
            needConfirm,
            longitude,
            latitude
          )
          
          if (confirmRes && confirmRes.code === 0) {
            uni.showToast({
              title: '订单已确认',
              icon: 'success'
            })
            // 刷新订单列表
            await fetchParticipatedOrders()
          } else {
            uni.showToast({
              title: confirmRes?.msg || '确认订单失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('确认订单失败:', error)
          uni.showToast({
            title: '确认订单失败，请稍后重试',
            icon: 'none'
          })
        }
      }
    }
  })
}

onMounted(async () => {
  await fetchPublishedOrders()
  uni.$on('showPublishModal', () => {
    publishModalRef.value?.showModal && publishModalRef.value.showModal()
  })
})

onUnmounted(() => {
  uni.$off('showPublishModal')
})
</script>
  
  <style lang="scss" scoped>
  .order-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
    position: relative;
    background: #f6f7fb;
    padding-bottom: calc(98rpx + env(safe-area-inset-bottom));
    padding-bottom: calc(98rpx + constant(safe-area-inset-bottom));
  }

  .order-header-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 480rpx;
    z-index: 0;
  }
  
  .fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background-color: transparent;
    padding-top: env(safe-area-inset-top);
    padding-top: constant(safe-area-inset-top);
  }
  
  .spacer {
    height: 100rpx; /* Adjust as needed for spacing */
    width: 100%;
    background-color: transparent;
  }

  .main-tabs {
    margin-top: 20rpx;
    position: relative;
    z-index: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 32rpx;
    color: #000;
    column-gap: 24rpx;

    .main-tab-item {
      flex: none;
      text-align: center;
      padding: 12rpx 24rpx;
      font-size: 32rpx;
      color: #000;
      position: relative;

      &.active {
        color: #000;
        font-weight: bold;

        &::after {
          content: '';
          position: absolute;
          bottom: -8rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 36rpx;
          height: 8rpx;
          border-radius: 4rpx;
          background-color: #007aff;
        }
      }
    }
  }
  
  .status-tabs {
    width: 100%;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    position: relative;
    z-index: 1;
    
    .status-tabs-container {
      display: flex;
      align-items: center;
      padding: 0 30rpx;
      gap: 24rpx;
      min-width: max-content;
    }
    
    .status-tab-item {
      flex: none;
      text-align: center;
      padding: 16rpx 24rpx;
      font-size: 30rpx;
      color: #000;
      white-space: nowrap;
      position: relative;
      
      &.active {
        color: #000;
        font-weight: 600;
        
        &::after {
          content: '';
          position: absolute;
          bottom: 8rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 24rpx;
          height: 4rpx;
          border-radius: 2rpx;
          background-color: #007aff;
        }
      }
    }
  }
  
  .order-list {
    flex: 1;
    background: transparent;
    padding: 0 30rpx 120rpx;
    padding-top: 20rpx;
    box-sizing: border-box;
    position: relative;
    z-index: 1;
    /* 固定头部高度：spacer(100) + main-tabs(约80) + status-tabs(约100) = 约280rpx，增加一些额外间距 */
    margin-top: 300rpx;
    height: calc(100vh - 300rpx);
  }
  
  .order-card {
    position: relative;
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
  }
  
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16rpx;
    
    .title-wrapper {
      display: flex;
      align-items: center;
      flex: 1;
      min-width: 0;
    }
    
    .order-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-right: 8rpx;
    }
    
    .buddy-type-badge {
      font-size: 24rpx;
      color: #F18F10;
      background-color: rgba(252, 231, 152, 0.42);
      padding: 4rpx 12rpx;
      border-radius: 8rpx;
      white-space: nowrap;
      flex-shrink: 0;
    }
    
    .order-tags {
      display: flex;
      gap: 12rpx;
      flex-shrink: 0;
    }
  }
  
  
  .status-tag {
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
    color: #fff;
    
    &.status-taking {
      background-color: #9c27b0;
    }
    
    &.status-in_progress {
      background-color: #f44336;
    }
    
    &.status-completed {
      background-color: #4caf50;
    }
    
    &.status-cancelled {
      background-color: #9e9e9e;
    }
    
    &.status-rejected {
      background-color: #ff9800;
    }
    
    &.status-pending_confirm {
      background-color: #2196f3;
    }
    
    &.status-pending_review {
      background-color: #ff5722;
    }
    
    &.status-pending_start {
      background-color: #9c27b0;
    }
  }
  
  .publish-time {
    font-size: 24rpx;
    color: #000;
    margin-bottom: 16rpx;
    display: block;
  }
  
  .event-time, .event-location {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #666;
    margin-bottom: 12rpx;
    
    .event-icon {
      width: 28rpx;
      height: 28rpx;
      margin-right: 8rpx;
    }
  }
  
  .detail-tags {
    display: flex;
    gap: 12rpx;
    margin-bottom: 20rpx;
    
    .detail-tag {
      padding: 6rpx 12rpx;
      background-color: #f0f0f0;
      border-radius: 16rpx;
      font-size: 22rpx;
      color: #666;
    }
  }
  
  .order-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;
    gap: 20rpx;
    background: linear-gradient(90deg, #DCEAFA 0%, #E6E4FF 35%, rgba(220, 234, 250, 0) 69%);
    padding: 10rpx 18rpx;
    border-radius: 16rpx;
    box-sizing: border-box;
  
  .participants {
    display: flex;
    align-items: center;
    flex: 1;
    
    .participant-avatars {
      display: flex;
      align-items: center;
      
      .participant-avatar {
        width: 44rpx;
        height: 44rpx;
        border-radius: 50%;
        border: 2rpx solid #fff;
        margin-left: -12rpx;
        
        &:first-child {
          margin-left: 0;
        }
      }
      
      .participant-more {
        width: 44rpx;
        height: 44rpx;
        border-radius: 50%;
        background-color: rgba(0, 0, 0, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        color: #666;
        margin-left: -12rpx;
        border: 2rpx solid #fff;
      }
    }
    
    .participant-count {
      font-size: 24rpx;
      color: #999;
      margin-left: 16rpx;
      white-space: nowrap;
    }
  }
  
  .action-section {
    display: flex;
    align-items: center;
    gap: 16rpx;
    flex-shrink: 0;
  }
    
    .price {
    font-size: 32rpx;
      font-weight: bold;
      color: #f44336;
    margin-right: 0;
    }
    
    .participated-actions {
      display: flex;
      gap: 12rpx;
      align-items: center;
    }
    
    .action-button {
      padding: 10rpx 24rpx;
      border-radius: 24rpx;
      font-size: 26rpx;
      color: #333;
      background-color: #eeeeee;
      border: none;
      line-height: 1.2;
      min-width: 140rpx;
      
      &::after {
        border: none;
      }
      
      &.cancel-btn {
        background-color: #eeeeee;
        color: #333;
        min-width: 100rpx;
      }
      
      &.confirm-btn {
        background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
        color: #fff;
        min-width: 120rpx;
      }
      
      &.action-completed,
      &.action-pending_review {
        background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
        color: #fff;
      }
    }
  }
  
  .card-bg {
    position: absolute;
    top: 0;
    right: 0;
  width: 180rpx;
  height: 180rpx;
  opacity: 0.15;
    pointer-events: none;
    
  .bg-image {
    width: 100%;
    height: 100%;
    }
  }
  </style>